import 'package:flutter/material.dart';
import '../models/nutrition.dart';
import '../services/api_service.dart';

class NutritionProvider with ChangeNotifier {
  final ApiService _apiService = ApiService();

  Nutrition? _nutritionData;
  bool _isLoading = false;
  int _searchMode = 0; // 0: 营养成分, 1: 食品分类, 2: 营养正序, 3: 营养倒序
  String _errorMessage = '';

  // Getters
  Nutrition? get nutritionData => _nutritionData;
  bool get isLoading => _isLoading;
  int get searchMode => _searchMode;
  String get errorMessage => _errorMessage;

  // 设置搜索模式
  void setSearchMode(int mode) {
    _searchMode = mode;
    notifyListeners();
  }

  // 获取营养成分
  Future<void> fetchNutritionData(String food) async {
    if (food.isEmpty) {
      _errorMessage = '请输入食品名称';
      notifyListeners();
      return;
    }

    _isLoading = true;
    _errorMessage = '';
    _nutritionData = null;
    notifyListeners();

    try {
      final response = await _apiService.getNutritionData(food, _searchMode);

      if (response.items.isNotEmpty) {
        _nutritionData = response.items[0];
      }

      _isLoading = false;
      notifyListeners();
    } catch (e) {
      _isLoading = false;
      _errorMessage = e.toString();
      notifyListeners();
    }
  }
}
